package com.moss.system.service.impl;

import com.moss.common.domain.TreeEntity;
import com.moss.common.entity.SysOrgEntity;
import com.moss.system.mapper.OrgMapper;
import com.moss.system.service.OrgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class OrgServiceImpl implements OrgService {


    @Resource
    OrgMapper orgMapper;


    @Override
    public List<SysOrgEntity> selectList(String orgId) {
        return orgMapper.selectList(orgId);
    }

    @Override
    public List<TreeEntity> buildTree(List<SysOrgEntity> orgList) {
        Set<Long> ids = orgList.stream()
                .map(SysOrgEntity::getOrgId)
                .collect(Collectors.toSet());

        List<SysOrgEntity> collect = orgList.stream()
                .filter(m -> !ids.contains(m.getParentId()))
                .peek(m -> m.setChildren(getChildrenList(m, orgList)))
                .collect(Collectors.toList());
        return collect.stream().map(TreeEntity::new).collect(Collectors.toList());
    }

    private List<SysOrgEntity> getChildrenList(SysOrgEntity root, List<SysOrgEntity> all) {
        return all.stream().filter(m -> Objects.equals(m.getParentId(), root.getOrgId())).peek(
                (m) -> m.setChildren(getChildrenList(m, all))
        ).collect(Collectors.toList());
    }
}
